package day08;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 对myfile.txt文件进行复制操作，要求使用异常捕获
 * 机制对流的异常进行捕获和处理，finally中
 * 要将流关闭
 * @author Bonnie
 *
 */
public class Test01 {
    public static void main(String[] args){
        File file = new File("myfile.txt");
        try {
            //创建文件
            file.createNewFile();
            //写入内容
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write("这里是myfile文件".getBytes());
            fileOutputStream.close();
        }catch (IOException ignored){
        }
        //复制文件
        BufferedOutputStream fileCopy = null;
        BufferedInputStream input = null;
        try {
            fileCopy = new BufferedOutputStream(new FileOutputStream("myfile_Copy.txt", true));
            input = new BufferedInputStream(Files.newInputStream(file.toPath()));
            byte[] bt = new byte[1024];
            int len;
            while ((len = input.read(bt)) != -1) {
                fileCopy.write(bt, 0, len);
            }
        }catch (IOException e){
            System.out.println("出错了");
        }finally {
            try {
                fileCopy.flush(); //刷新缓冲区
                fileCopy.close();
                input.close();
            } catch (IOException ignored) {
            }
        }
    }

}
